<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="90px">
      <div class="bottomLine">选择事件
        <div style="width:200px;display: block;float: right;">设置关联属性
          <el-switch
            v-model="switchValue"
            active-color="#13ce66"
            inactive-color="#c0ccda">
          </el-switch>
        </div>
      </div>
      <el-row class="bottomLine">
        <el-form-item label="应用:" label-width="40">
          <el-select v-model="queryParams.applicationCode"  multiple  placeholder="请选择应用">
            <el-option
              v-for="dict in applicationList"
              :key="dict.appCode"
              :label="dict.name"
              :value="dict.appCode"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-row>
      <el-row :gutter="10" class="bottomLine">
        <el-form-item label="初始行为" prop="status">
          <el-popover
            placement="bottom-start"
            width="800"
            trigger="click"
          >
            <PanelSelect ref="panelSelect" @selected="selected" :eventObj="1"/>
            <el-input slot="reference" v-model="queryParams.initTypeName" placeholder="点击选择事件" readonly
                      style="width: 200px;" suffix-icon="el-icon-arrow-down">
            </el-input>
          </el-popover>
          <el-link type="primary" :underline="false" style="padding-left:20px;" @click="addRule('initRuleTypes')">
            <i class="el-icon-plus"></i> <span class="innerContent">筛选</span>
          </el-link>
        </el-form-item>

      </el-row>
      <el-row v-show="queryParams.relationFlag">
        <el-form-item label="关联属性" style="display: block;padding-left:10px;">
          <el-select v-model="queryParams.initRelationType" style="width:220px">
            <el-option
              v-for="dict in eventTypeOptions"
              :key="dict.eventType"
              :label="dict.eventTypeName"
              :value="dict.eventType"
            />
          </el-select>
        </el-form-item>
      </el-row>
      <el-row v-show="queryParams.initRuleTypes.length>0">
        <el-form-item label="" style="display: block;padding-left:80px;" label-width="60px">
					<AndOrLine style="height: calc(100% - 10px);" v-show="queryParams.initRuleTypes.length>1" v-model="queryParams.beginConditionRelation"></AndOrLine>
          <p style="margin: 0 0 10px;" v-for="(eventItem,index) in queryParams.initRuleTypes">
            <el-select v-model="eventItem.eventType" style="width:120px;margin-right: 10px;"
                       @change="eventTypeChange(queryParams.initRuleTypes,index)">
              <el-option
                v-for="dict in eventTypeOptions"
                :key="dict.id"
                :label="dict.eventTypeName"
                :value="dict.id"
              />
            </el-select>
            <el-select v-model="eventItem.eventItem" style="width:120px;margin-right: 10px;"  value-key="id">
              <el-option
                v-for="dict in allEventItemListOpts[eventItem.eventType]"
                :key="dict.id"
                :label="dict.eventItemName"
                :value="dict"
              />
            </el-select>
            <el-select v-model="eventItem.eventItemExpression" style="width:120px;margin-right: 10px;">
              <el-option
                v-for="dict in  eventPropertysOptions[eventItem.eventItem.valueType]"
                :key="dict.id"
                :label="dict.eventItemExpression"
                :value="dict.eventItemCode"
              />
            </el-select>
            <el-input v-model="eventItem.value1Str" type="text" controls-position="right" style="width:100px"
                      v-show="eventItem.eventItemExpression!='between'"></el-input>
            <span v-show="eventItem.eventItemExpression=='between'">
                <el-input v-model="eventItem.value1Str" type="text" controls-position="right"
                          style="width:90px"></el-input>与
                <el-input v-model="eventItem.value2Str" type="text" controls-position="right"
                          style="width:90px"></el-input>之间
            </span>
            <el-link type="primary" :underline="false" style="padding-left:20px;font-size:18px"
                     @click="removeRule(queryParams.initRuleTypes,index)">
              <i class="el-icon-remove"></i>
            </el-link>
          </p>

        </el-form-item>
      </el-row>
      <el-row :gutter="10" class="bottomLine">
        <el-form-item label="后续行为" prop="status">
          <el-popover
            placement="bottom-start"
            width="800"
            trigger="click"
          >
            <PanelSelect ref="panelSelect" @selected="selected" :eventObj="2"/>
            <el-input slot="reference" v-model="queryParams.nextTypeName" placeholder="点击选择事件" readonly
                      style="width: 200px;" suffix-icon="el-icon-arrow-down">
            </el-input>
          </el-popover>
          <el-link type="primary" :underline="false" style="padding-left:20px;" @click="addRule('nextRuleTypes')">
            <i class="el-icon-plus"></i> <span class="innerContent">筛选</span>
          </el-link>
        </el-form-item>
      </el-row>
      <el-row v-show="queryParams.relationFlag">
        <el-form-item label="关联属性" style="display: block;padding-left:10px;">
          <el-select v-model="queryParams.initRelationType" style="width:220px">
            <el-option
              v-for="dict in eventTypeOptions"
              :key="dict.id"
              :label="dict.eventTypeName"
              :value="dict.eventType"
            />
          </el-select>
        </el-form-item>
      </el-row>
      <el-row v-show="queryParams.nextRuleTypes.length>0">
        <el-form-item label="" style="display: block;padding-left:80px;" label-width="60px">
						<AndOrLine style="height: calc(100% - 10px);" v-show="queryParams.nextRuleTypes.length>1" v-model="queryParams.nextConditionRelation"></AndOrLine>
          <p style="margin: 0 0 10px;" v-for="(eventItem,index) in queryParams.nextRuleTypes">
            <el-select v-model="eventItem.eventType" style="width:120px;margin-right: 10px;"
                       @change="eventTypeChange(queryParams.nextRuleTypes,index)">
              <el-option
                v-for="dict in eventTypeOptions"
                :key="dict.id"
                :label="dict.eventTypeName"
                :value="dict.id"
              />
            </el-select>
            <el-select v-model="eventItem.eventItem" style="width:120px;margin-right: 10px;"  value-key="id">
              <el-option
                v-for="dict in allEventItemListOpts[eventItem.eventType]"
                :key="dict.id"
                :label="dict.eventItemName"
                :value="dict"
              />
            </el-select>
            <el-select v-model="eventItem.eventItemExpression" style="width:120px;margin-right: 10px;">
              <el-option
                v-for="dict in  eventPropertysOptions[eventItem.eventItem.valueType]"
                :key="dict.id"
                :label="dict.eventItemExpression"
                :value="dict.eventItemCode"
              />
            </el-select>
            <el-input v-model="eventItem.value1Str" type="text" controls-position="right" style="width:100px"
                      v-show="eventItem.eventItemExpression!='between'"></el-input>
            <span v-show="eventItem.eventItemExpression=='between'">
                <el-input v-model="eventItem.value1Str" type="text" controls-position="right"
                          style="width:90px"></el-input>与
                <el-input v-model="eventItem.value2Str" type="text" controls-position="right"
                          style="width:90px"></el-input>之间
            </span>
            <el-link type="primary" :underline="false" style="padding-left:20px;font-size:18px"
                     @click="removeRule(queryParams.nextRuleTypes,index)">
              <i class="el-icon-remove"></i>
            </el-link>
          </p>

        </el-form-item>
      </el-row>
      <el-form-item label="按" prop="status" class="bottomLine">
        <el-select v-model="queryParams.groupEventType" placeholder="请选营收事件" clearable size="small" value-key="id">
          <el-option
            v-for="dict in eventTypeOptions"
            :key="dict.id"
            :label="dict.eventTypeName"
            :value="dict"
          />
        </el-select>
        <el-link type="primary" :underline="false" style="padding-left:20px;">
          <i class="el-icon-setting"></i> <span class="innerContent">查看</span>
        </el-link>
      </el-form-item>
      <el-row v-show="queryParams.userAttributes.length>0">
        <el-form-item label="" style="display: block;padding-left:80px;" label-width="60px">
					<AndOrLine style="height: calc(100% - 10px);" v-show="queryParams.userAttributes.length>1" v-model="queryParams.userConditionRelation"></AndOrLine>
          <p v-for="(userAttr,index) in queryParams.userAttributes">
            <el-select v-model="userAttr.userAttribute" style="width:120px;margin-right: 10px;" value-key="id">
              <el-option
                v-for="dict in userAttributeOptions"
                :key="dict.id"
                :label="dict.attributeRemark"
                :value="dict"
              />
            </el-select>
            <el-select v-model="userAttr.valueExpression" style="width:120px;margin-right: 10px;">
              <el-option
                v-for="dict in eventPropertysOptions[userAttr.userAttribute.dataType]"
                :key="dict.eventItemCode"
                :label="dict.eventItemExpression"
                :value="dict.eventItemCode"
              />
            </el-select>
            <el-input v-model="userAttr.value1Str" type="text" controls-position="right" style="width:100px"
                      v-show="userAttr.valueExpression!='between'"></el-input>
            <span v-show="userAttr.valueExpression=='between'">
                <el-input v-model="userAttr.value1Str" type="text" controls-position="right"
                          style="width:90px"></el-input>与
                <el-input v-model="userAttr.value2Str" type="text" controls-position="right"
                          style="width:90px"></el-input>之间
            </span>
            <el-link type="primary" :underline="false" style="padding-left:20px;font-size:18px"
                     @click="removeRule(queryParams.userAttributes,index)">
              <i class="el-icon-remove"></i>
            </el-link>
          </p>

        </el-form-item>
      </el-row>
      <el-row class="bottomLine">
        <el-link type="primary" :underline="false" style="padding-left:20px;"  @click="addUserAttribute">
          <i class="el-icon-plus"></i> <span class="innerContent">且用户符合</span>
        </el-link>
      </el-row>
    </el-form>
    <el-container>

      <el-main>
        <el-row :gutter="10">
          <el-col :span="6">
            <el-date-picker
              v-model="queryParams.dateRange"
              size="small"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              @change="queryDtaFun"
              range-separator="-"
              :picker-options="pickerOptions"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-col>
          <el-col :span="2">
            <el-select v-model="queryParams.dateType" @change="queryDtaFun" style="width:80px;"  clearable size="small">
              <el-option label="合计" value="sum"></el-option>
              <el-option label="按天" value="day"></el-option>
              <el-option label="按周" value="week"></el-option>
              <el-option label="按月" value="month"></el-option>
            </el-select>
          </el-col>
          <el-col :span="3" >
            <el-select @change="queryDtaFun" v-model="queryParams.methodValue" style="width:100px;" clearable size="small">
              <el-option label="显示设置" value="01"></el-option>
              <el-option label="最大值" value="02"></el-option>
              <el-option label="最小值" value="03"></el-option>
              <el-option label="平均值" value="04"></el-option>
              <el-option label="四分位" value="05"></el-option>
              <el-option label="中位数" value="06"></el-option>
            </el-select>
          </el-col>
        </el-row>
        <BoxplotChart :chart-data="chartData" :chart-title="chartTitle" :style="{width:'100%',height:'300px'}"></BoxplotChart>
        <el-table
          :data="tableData"
          style="width: 100%;margin-bottom: 20px;"
          row-key="id"
          border
          default-expand-all
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
          <el-table-column
            prop="date"
            label=""
            sortable
            width="180">
          </el-table-column>
          <el-table-column
            prop="name"
            label="间隔时间中位数"
            sortable
            width="180">
          </el-table-column>
          <el-table-column
            prop="address"
            label="最大值">
          </el-table-column>
          <el-table-column
            prop="address"
            label="最小值">
          </el-table-column>
          <el-table-column
            prop="address"
            label="上四分位">
          </el-table-column>
          <el-table-column
            prop="address"
            label="下四分位">
          </el-table-column>
          <el-table-column
            prop="address"
            label="人均转化时间">
          </el-table-column>
          <el-table-column
            prop="address"
            label="转化用户数">
          </el-table-column>
        </el-table>
      </el-main>

    </el-container>
  </div>
</template>

<script>
import {getAllSiteFlowList, getIntervalQueryData, getLTVQueryData} from "@/api/analytics/basemeasure";
import PanelSelect from "@/components/PanelSelect";
import BoxplotChart from "@/views/report/interval/comments/BoxplotChart";
import AndOrLine from '@/components/AndOrLine/index.vue'
import {allEventItemsOptions, eventTypeOptions} from "@/api/config/item";
import {listAllPropertyResult} from "@/api/config/property";
import {listApplication} from "@/api/config/application";
import {getAllEventMethodResult} from "@/api/config/emethod";
import {getUserAttributeList} from "@/api/config/userattribute";
import {parseTime} from "@/utils/ruoyi";


export default {
  name: "interval",
  components: {
    BoxplotChart,PanelSelect,AndOrLine
  },
  data() {
    return {
      showNum:7,
      chartData:{},
      chartTitle:[],
      switchValue: false,
      startFlag:'start',
      statusOptions: [],
      params: {
        dateRange: ''
      },
      lineChartData: {
        actualData: []
      },
      // 遮罩层
      loading: true,
      tableData: [{
        id: 3,
        date: '$APP激活的启动时长',
        name: '368',
        address: '28.59',
        children: [{
          id: 31,
          date: '4-15 (四)',
          name: '368',
          address: '28.59%'
        }, {
          id: 32,
          date: '4-16 (五)',
          name: '286',
          address: '19.15%'
        }]
      }],

      // 查询参数
      queryParams: {
        applicationCode:[],
        groupEventType:{},
        initTypeName:'',
        initEventType:'',
        initRuleTypes:[],
        initRelationType:'',
        nextTypeName:'',
        nextEventType:'',
        nextRuleTypes:[],
        nextRelationType:'',
        userAttributes:[],
        dateRange:[parseTime(new Date(),'{y}-{m}-{d}'),parseTime(new Date(),'{y}-{m}-{d}')],
        name: undefined,
        status: undefined,
        methodValue:'01',
        dateType:'sum',
				beginConditionRelation: 'and',
				nextConditionRelation: 'and',
				userConditionRelation: 'and'
      },
      pickerOptions: {
        shortcuts: [{
          text: '今日',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '昨日',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 1);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '本周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            const day = start.getDay() || 7;
            var newStart = new Date(start.getFullYear(), start.getMonth(), start.getDate() + 1 - day);
            picker.$emit('pick', [newStart, end]);
          }
        }, {
          text: '上周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      drawer: false,
      direction: 'rtl',
      formLabelWidth: '90px',
      index: 1,
      ruleTypes3Flag: 0,
      applicationList:[],
      eventTypeOptions: [],
      allEventItemListOpts:{},
      eventPropertysOptions:{},
      referrerTypeOptions: [],
      userAttributeOptions:[],
      // 表单参数
      form: {}
    };
  },
  created() {
    this.getEventTypeList();
    this.getAllEventItemsList();
    this.getApplicationList();
    this.getUserAttributeList();
    this.getAllFlowList();
  },
  methods: {

    getSummaries(param) {
      const {columns, data} = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总价';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[index] += ' 元';
        } else {
          sums[index] = 'N/A';
        }
      });

      return sums;
    },
    getAllFlowList() {
      var param = {};
      getAllSiteFlowList(param).then(response => {
        this.lineChartData.actualData = response.data;
      });
    },
    selected(item,type) {
      if(type===1){
        this.queryParams.initTypeName = item.eventTypeName;
        this.queryParams.initEventType=item.eventType;
      }else{
        this.queryParams.nextTypeName=item.eventTypeName;
        this.queryParams.nextEventType=item.eventType;
      }

    },
    getApplicationList() {
      listApplication({status: 'Y'}).then(response => {
        this.applicationList = response.rows;
        let that=this;
        this.applicationList.forEach(function(app){
          if(app.defaultFlag==='Y'){
            that.queryParams.applicationCode.push(app.appCode);
          }
        });
      });
    },
    getEventTypeList() {
      var param = {status: 'Y'};
      eventTypeOptions(param).then(response => {
        this.eventTypeOptions = response.data;
      });
    },
    getAllEventItemsList(){
      allEventItemsOptions().then(response => {
        this.allEventItemListOpts = response.data;
      });
      listAllPropertyResult().then(response => {
        this.eventPropertysOptions = response.data;
      });
      getAllEventMethodResult().then(response => {
        this.allEventItemMethodOpts = response.data;
      });
    },
    getUserAttributeList() {
      var param = {status: 'Y'};
      getUserAttributeList(param).then(response => {
        this.userAttributeOptions = response.data;
      });
    },
    addRule(name){
      let eventItem={
        eventType:'',
        eventItem:{},
        eventItemExpression:'',
        valueType:'',
        value1Str:'',
        value2Str:'',
      };
      this.queryParams[name].push(eventItem);
    },

    removeRule(array,index){
      array.splice(index,1);
    },
    addUserAttribute(){
      let userAttribute={
        userAttribute:{},
        valueExpression:'',
        dataType:'',
        valueType:'',
        value1Str:'',
        value2Str:'',
      };
      this.queryParams.userAttributes.push(userAttribute);
    },
    queryDtaFun(){
      console.log(this.queryParams);
      let requestJson=JSON.stringify(this.queryParams);
      getIntervalQueryData({requestJson:requestJson}).then(response => {
        console.log(response.data);

      });
    },
  }


};
</script>
<style lang="scss" scoped>
.el-form-item {
  margin-bottom: 10px;
}
.innerContent {
  font-size: 14px;
  line-height: 20px;
  color: #307ef2;
  cursor: pointer;
}
.bottomLine{
  width:100%;
  display:inline-block;
  border-bottom: 1px solid #e9f0f7;
  margin-bottom: 10px;
  padding-bottom:10px;
}

</style>
